﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Scoreboard.Model;
using Scoreboard.Data;
using Scoreboard.Basement;

namespace Scoreboard.CommonViews
{
	public class ContentTemplateSelector
	{
		public static Group GetGroup(DependencyObject obj)
		{
			return (Group)obj.GetValue(GroupProperty);
		}

		public static void SetGroup(DependencyObject obj, Group value)
		{
			obj.SetValue(GroupProperty, value);
		}
		
		public static readonly DependencyProperty GroupProperty =
			DependencyProperty.RegisterAttached("Group", typeof(Group), typeof(ContentTemplateSelector), new PropertyMetadata(null, GroupChangedCallback));

		private static Dictionary<Group, ContentControl> _groups = new Dictionary<Group, ContentControl>();

		private static void GroupChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var contentControl = d as ContentControl;
			var group = e.NewValue as Group;

			string templateKey = GetTemplateKey(group);

			contentControl.ContentTemplate = contentControl.Resources[templateKey] as DataTemplate;

			_groups[group] = contentControl;
			group.PropertyChanged += GroupPropertyChanged;
		}

		private static void GroupPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			var group = sender as Group;
			if (e.PropertyName != "SelfForTemplate")
			{
				return;
			}
			var contentControl = _groups[group];
			contentControl.ContentTemplate = contentControl.Resources[GetTemplateKey(group)] as DataTemplate;
		}

		private static string GetTemplateKey(Group group)
		{
			if (group.Participants.Count > 2)
			{ 
				return "TableGroupTemplate"; 
			}
			if (!AppSettings.KeepsScore)
			{
				return "ScorelessGameGroupTemplate";
			}
			if (group.Games.Count == 1)
			{
				return "GameGroupTemplate";
			}
			
			return "FutureGameGroupTemplate";
		}
	}
}
